/**
 * Copyright (C) 2010 Krishna Sundaresan <calvinkrishy@gmail.com>
 *      
 * This file is part of webos-datecalculator application.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

function CreateEventAssistant(forDate){
    this.evtDate = forDate;
}

CreateEventAssistant.prototype.init = function(){
    this.accntSetup();
}

CreateEventAssistant.prototype.accntSetup = function(){

    this.controller.serviceRequest('palm://com.palm.accounts/crud', {
        method: 'listAccounts',
        onSuccess: this.setAccountId.bind(this),
        onFailure: this.handleErrResponse.bind(this)
    })
    
}

CreateEventAssistant.prototype.setAccountId = function(response){

    Mojo.Log.info(Object.toJSON(response))
 
    if (typeof response.list[0] != "undefined") {
        this.acctId = response.list[0].accountId;
        this.controller.serviceRequest('palm://com.palm.calendar/crud', {
            method: 'listCalendars',
            parameters: {
                "accountId": this.acctId
            },
            onSuccess: this.calSetup.bind(this),
            onFailure: this.handleErrResponse.bind(this)
        })
    }
    else {
    
        Mojo.Log.info('New account will be created')
        this.setup = {
            "username": 'dateCalculator',
            "domain": 'com.example.datecalculator',
            "displayName": 'Date Calculator',
            "icons": {
                'largeIcon:string': 'smallIcon:string'
            },
            "dataTypes": ['Calendar'],
            "isDataReadOnly": false
        }
        
        this.controller.serviceRequest('palm://com.palm.accounts/crud', {
            method: 'createAccount',
            parameters: this.setup,
            onSuccess: this.setAccountId.bind(this),
            onFailure: this.handleErrResponse.bind(this)
        })
        
    }
    
}

CreateEventAssistant.prototype.calSetup = function(response){

    if (typeof response.calendars[0] != "undefined") {
        this.calId = response.calendars[0].calendarId;
    }
    else {
        this.controller.serviceRequest('palm://com.palm.calendar/crud', {
            method: 'createCalendar',
            parameters: {
                "accountId": this.acctId,
                "calendar": {
                    "calendarId": '',
                    "name": 'DateCalculator Calendar'
                }
            },
            onSuccess: this.setCalId.bind(this),
            onFailure: this.handleErrResponse.bind(this)
        })
    }
}

CreateEventAssistant.prototype.setCalId = function(response){
    this.calId = response.calendarId;
}

CreateEventAssistant.prototype.findValues = function(){

    Mojo.Log.info('Start Time' + this.evtDate);
	Mojo.Log.info('End time ' + this.evtEndTime);
 	
	this.event['startTimestamp'] = this.evtDate.getTime();
	this.event['endTimestamp'] = this.evtEndTime.getTime();

    if(this.event['startTimestamp'] >= this.event['endTimestamp']){
        Mojo.Controller.errorDialog($L('Start time should be before the end time'))
        return false;
    }

    Mojo.Log.info('Alarm option set to ' + this.alrm['alarm']);

	this.event['alarm'] = this.alrm['alarm'];
	this.event['subject'] = this.event['subject'] == "" ? "New Event" : this.event['subject']; 
	
	return true;

}

CreateEventAssistant.prototype.checkUpdate = function(event){
	
	//All day event
	if(event.value){

        this.controller.get('timeDrawer').mojo.setOpenState(false)
	    this.alrm = DateCalculatorModels.dayModel
        this.controller.setWidgetModel('alarm', this.alrm)

	} else {

        this.controller.get('timeDrawer').mojo.setOpenState(true)
	    this.alrm = DateCalculatorModels.weekModel
        this.controller.setWidgetModel('alarm', this.alrm)
		
	}
	
}

CreateEventAssistant.prototype.setup = function(){

    this.init();

    this.evtEndTime = new Date(this.evtDate.getTime());
	this.evtEndTime.setTime(this.evtEndTime.getTime() + 3600000)
	
    this.event = {
        "subject": "",
        "startTimestamp": "",
		"endTimestamp": "",
        "st": this.evtDate,
		"et": this.evtEndTime,
        "allday": true,
        "note": "",
        "location": "",
        "alarm": "none"
    };
	
	this.alrm = DateCalculatorModels.dayModel
	Mojo.Log.info(this.alrm)
    
    $('create-header').update('New Event for ' + this.evtDate.toDateString());
    this.controller.setupWidget('subject', {
		modelProperty: 'subject',
		hintText: $L('Event'),
		textCase: Mojo.Widget.steModeTitleCase 
    }, this.event);
    this.controller.setupWidget('startTimestamp', {
		label: 'Start Time',
        modelProperty: 'st'
    }, this.event);
    this.controller.setupWidget('endTimestamp', {
        label: 'End Time',
		modelProperty: 'et'
    }, this.event);
    this.controller.setupWidget('allDay', {
        modelProperty: 'allday'
    }, this.event);
    this.controller.setupWidget('note', {
        modelProperty: 'note',
		multiline: true,
		hintText: 'Notes'
    }, this.event);
    this.controller.setupWidget('location', {
        modelProperty: 'location',
		hintText: $L('Event\'s Location')
    }, this.event);
    this.controller.setupWidget('alarm', {
        labelPlacement: Mojo.Widget.labelPlacementRight,
		label: $L('Alarm'),
		modelProperty: 'alarm'
    }, this.alrm);
	this.controller.setupWidget('timeDrawer', {unstyled:true}, {open:false})
    
	this.addHandler = this.add.bind(this);
	this.handleCheck = this.checkUpdate.bind(this);
	this.controller.listen('allDay', Mojo.Event.propertyChange, this.handleCheck);
    this.controller.listen('add_button', Mojo.Event.tap, this.addHandler);
    
};

CreateEventAssistant.prototype.add = function(){

    this.event["calendarId"] = this.calId;
    
	if(!this.findValues()){
		return
	}
	
    Mojo.Log.info(Object.toJSON(this.event))
	
    this.controller.serviceRequest('palm://com.palm.calendar/crud', {
        method: 'createEvent',
        parameters: {
            "calendarId": this.event.calendarId,
            "event": this.event
        },
        onSuccess: this.handleAddResponse.bind(this),
        onFailure: this.handleErrResponse.bind(this)
    })

}

CreateEventAssistant.prototype.handleAddResponse = function(response){
	
    this.evtId = response.eventId;

    Mojo.Log.info(this.evtId)
	
    this.controller.showAlertDialog({
        title: $L("Event Created"),
        message: $L("An event has been created for " + this.evtDate.toDateString()),
        choices: [{
            label: $L('OK'),
            value: "ok",
            type: "affirmative"
        }]
    });
}

CreateEventAssistant.prototype.cleanup = function(event){

    this.controller.stopListening('allDay', Mojo.Event.propertyChange, this.handleCheck);
    this.controller.stopListening('add_button', Mojo.Event.tap, this.addHandler);

};

CreateEventAssistant.prototype.handleErrResponse = function(response){
    
	Mojo.Log.error(Object.toJSON(response))
    $('response').update("Error service response: <br><br>" + this.evtDate.getUTCMilliseconds());

}
